package com.ydcycloud.admin.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.smart.mvc.exception.ValidateException;
import com.smart.mvc.model.Result;
import com.smart.mvc.provider.PasswordProvider;
import com.smart.mvc.validator.Validator;
import com.smart.mvc.validator.annotation.ValidateParam;
import com.smart.sso.rpc.Permission;
import com.smart.sso.rpc.Permissionable;
import com.smart.sso.rpc.Role;
import com.smart.sso.rpc.RolePermission;
import com.smart.sso.rpc.UserRole;
import com.smart.util.StringUtils;
import com.ydcycloud.sys.controller.BaseAdminController;

/**
 * 
 * ClassName: ManagerController 
 * @author hdt
 * @date 2016年10月28日 下午3:38:23
 * @Version 
 * @Description: TODO
 */
@Controller
@RequestMapping("/admin")
public class ManagerController extends BaseAdminController{

	@RequestMapping(value = {"admin","index"},method = RequestMethod.GET)
	public ModelAndView execute(HttpSession httpSession) {
		
		Map<String, Object> model=new HashMap<String, Object>(2);
		model.put("sessionAdmin", getSessionAdmin(httpSession));
		
		return new ModelAndView("admin/index",model);
	}

	@RequestMapping(value = "menu", method = RequestMethod.GET)
	public @ResponseBody Result menu(HttpServletRequest request) {
		Object list = request.getSession().getAttribute(Permissionable.SESSION_USER_MENU);
		// 如果配置的权限拦截器，则获取登录用户权限下的菜单，没有权限拦截限制的情况下，获取当前系统菜单呈现
		return Result.createSuccessResult().setData(list == null ? request.getSession().getAttribute(Permissionable.APPLICATION_MENU) : list);
	}
	
	@RequestMapping(value="editPassword",method=RequestMethod.GET)
	public String edPassword(){
		
		return "admin/admin/editPassword";
	}
	
	@RequestMapping(path="manager",method = RequestMethod.GET)
	public String manager() {
		return "/admin/admin/manager";
	}
	
	@RequestMapping(value = "manager/list", method = RequestMethod.GET)
	public @ResponseBody Result list(@ValidateParam(name = "登录名 ") String account,
			@ValidateParam(name = "开始页码", validators = { Validator.NOT_BLANK }) Integer pageNo,
			@ValidateParam(name = "显示条数 ", validators = { Validator.NOT_BLANK }) Integer pageSize) {
		return Result.createSuccessResult().setData(managerService.findPaginationByAccount(account,pageNo,pageSize));
	}
	
	/**
	 * 修改密码
	 * @Description: TODO
	 * @param password
	 * @param rePassword
	 * @param session
	 * @return   
	 * Result  
	 * @throws
	 * @author hdt
	 * @date 上午11:53:55
	 */
	@RequestMapping(path="updatePassword",method=RequestMethod.POST)
	public @ResponseBody Result updatePassword(
			@ValidateParam(name="密码",validators=Validator.NOT_NULL) String password,
			@ValidateParam(name="确认密码",validators=Validator.NOT_NULL) String rePassword,HttpSession session){
		
		if(!password.equals(rePassword)){
			return Result.createErrorResult(null, "两次密码不一致");
		}
		managerService.updatePwd(getSessionAdminId(session), password);
		return Result.createSuccessResult();
	}
	
	@RequestMapping(value="role",method=RequestMethod.GET)
	public String role(){
		
		return "admin/admin/role";
	}
	
	/**
	 * 加载角色
	 * @Description: TODO
	 * @param httpSession
	 * @return   
	 * Result  
	 * @throws
	 * @author hdt
	 * @date 上午11:55:45
	 */
	@RequestMapping(value="role/listRole")
	public @ResponseBody Result roleList(
			@RequestParam(defaultValue="1") @ValidateParam(name = "开始页码", validators = { Validator.NOT_BLANK })Integer pageNo,
			@ValidateParam(name = "显示条数 ", validators = { Validator.NOT_BLANK }) Integer pageSize,
			@ValidateParam(name = "学员名称") String roleName,
			HttpSession httpSession){
		
		Result r = managerService.listRole(pageNo,pageSize,roleName,getSessionAdminId(httpSession)); 
		
		return r;
	}
	
	/**
	 * 
	 * @Description: TODO
	 * @param ids
	 * @param isEnable
	 * @return   
	 * Result  
	 * @throws
	 * @author hdt
	 * @date 下午4:02:38
	 */
	@RequestMapping(value = "role/enable", method = RequestMethod.POST)
	public @ResponseBody Result enable(
			@ValidateParam(name = "ids", validators = { Validator.NOT_BLANK })String ids,
			@ValidateParam(name = "是否启用 ", validators = { Validator.NOT_BLANK }) Boolean isEnable) {
		managerService.enable(isEnable, getAjaxIntegerIds(ids));
		return Result.createSuccessResult();
	}
	
	/**
	 * 去到增加角色页面
	 * @Description: TODO
	 * @param id
	 * @param model
	 * @return   
	 * String  
	 * @throws
	 * @author hdt
	 * @date 上午8:58:51
	 */
	@RequestMapping(value = "role/edit", method = RequestMethod.GET)
	public String edit(@ValidateParam(name = "id") Integer id, Model model) {
		Role role;
		if (id == null) {
			role = new Role();
		}
		else {
			role = managerService.getRole(id);
		}
		model.addAttribute("role", role);
		return "/admin/admin/roleEdit";
	}
	/**
	 * 保存角色
	 * @Description: TODO
	 * @param id
	 * @param appId
	 * @param name
	 * @param sort
	 * @param description
	 * @param isEnable
	 * @return   
	 * Result  
	 * @throws
	 * @author hdt
	 * @date 上午9:03:04
	 */
	@RequestMapping(value = "role/save", method = RequestMethod.POST)
	public @ResponseBody Result save(@ValidateParam(name = "ID") Integer id,
			@ValidateParam(name = "角色名", validators = { Validator.NOT_BLANK }) String name,
			@ValidateParam(name = "排序", validators = { Validator.NOT_BLANK }) Integer sort,
			@ValidateParam(name = "描述") String description,
			@ValidateParam(name = "是否启用 ", validators = { Validator.NOT_BLANK }) Boolean isEnable) {
		Role role;
		if (id == null) {
			role = new Role();
		}
		else {
			role = managerService.getRole(id);
		}
		role.setName(name);
		role.setSort(sort);
		role.setDescription(description);
		role.setIsEnable(isEnable);
		managerService.saveOrUpdateRole(role);
		return Result.createSuccessResult();
	}
	/**
	 * 加载权限
	 * @Description: TODO
	 * @param isEnable
	 * @return   
	 * List<Permission>  
	 * @throws
	 * @author hdt
	 * @date 上午10:10:09
	 */
	@RequestMapping(value="permission/nodes",method=RequestMethod.GET)
	public @ResponseBody List<Permission> nodes(
					@ValidateParam(name = "是否启用 ") Boolean isEnable,HttpSession httpSession) {
		List<Permission> list = managerService.listPermission();
		if(list!=null&&list.size()>0){
			httpSession.setAttribute("appId", httpSession.getAttribute("appId")==null?list.get(0).getAppId():httpSession.getAttribute("appId"));
		}
		Permission permission = new Permission();
		permission.setId(null);
		permission.setParentId(-1);
		permission.setSort(1);
		permission.setName("根节点");
		list.add(0, permission);
		return list;
	}
	
	
	@RequestMapping(value = "role/allocate", method = RequestMethod.GET)
	public @ResponseBody Result allocate(
			@ValidateParam(name = "角色ID", validators = { Validator.NOT_BLANK }) Integer roleId) {
		return Result.createSuccessResult().setData(managerService.findByRoleId(roleId));
	}
	
	/**
	 * 保存用角色权限
	 * @Description: TODO
	 * @param roleId
	 * @param permissionIds
	 * @param session
	 * @return   
	 * Result  
	 * @throws
	 * @author hdt
	 * @date 上午11:15:41
	 */
	@RequestMapping(value = "role/allocateSave", method = RequestMethod.POST)
	public @ResponseBody Result allocateSave(
			@ValidateParam(name = "角色ID", validators = { Validator.NOT_BLANK }) Integer roleId,
			@ValidateParam(name = "权限IDS ", validators = { Validator.NOT_BLANK }) String permissionIds,HttpSession session) {
		List<Integer> idList = getAjaxIntegerIds(permissionIds);
		List<RolePermission> list = new ArrayList<RolePermission>();
		Integer appId =  (Integer) session.getAttribute("appId");
		Integer permissionId;
		for (Iterator<Integer> i$ = idList.iterator(); i$.hasNext(); list.add(new RolePermission(appId, roleId, permissionId))) {
			permissionId = i$.next();
		}
		return Result.createSuccessResult(managerService.allocate(roleId, list), "授权成功");
	}
	
	/**
	 * 编辑用户
	 * @Description: TODO
	 * @param id
	 * @param model
	 * @return   
	 * String  
	 * @throws
	 * @author hdt
	 * @date 下午3:16:04
	 */
	@RequestMapping(value = "manager/edit", method = RequestMethod.GET)
	public String managerEdit(@ValidateParam(name = "id") Integer id, Model model) {
		com.smart.sso.rpc.Manager manager ;
		if (id == null) {
			manager = new com.smart.sso.rpc.Manager();
		}
		else {
			manager = managerService.getManager(id);
		}
		model.addAttribute("manager", manager);
		return "/admin/admin/managerEdit";
	}
	
	/**
	 * 
	 * @Description: TODO
	 * @param id
	 * @param account
	 * @param password
	 * @param isEnable
	 * @return   
	 * Result  
	 * @throws
	 * @author hdt
	 * @date 下午2:42:46
	 */
	@RequestMapping(value = "manager/save", method = RequestMethod.POST)
	public @ResponseBody Result save(@ValidateParam(name = "ID") Integer id,
			@ValidateParam(name = "登录名", validators = { Validator.NOT_BLANK }) String account,
			@ValidateParam(name = "密码 ") String password,
			@ValidateParam(name = "是否启用 ", validators = { Validator.NOT_BLANK }) Boolean isEnable) {
		com.smart.sso.rpc.Manager manager;
		if (id == null) {
			if (StringUtils.isBlank(password)) {
				throw new ValidateException("密码不能为空");
			}
			manager = new com.smart.sso.rpc.Manager();
			manager.setCreateTime(new Date());
		}
		else {
			manager = managerService.getManager(id);
		}
		manager.setAccount(account);
		if (StringUtils.isNotBlank(password)) {
			manager.setPassword(PasswordProvider.encrypt(password));
		}
		manager.setIsEnable(isEnable);
		managerService.saveOrUpdateManager(manager);
		return Result.createSuccessResult();
	}


	/**
	 * 启用禁用用户
	 * @Description: TODO
	 * @param ids
	 * @param isEnable
	 * @return   
	 * Result  
	 * @throws
	 * @author hdt
	 * @date 下午2:45:37
	 */
	@RequestMapping(value = "manager/enable", method = RequestMethod.POST)
	public @ResponseBody Result enableManager(@ValidateParam(name = "ids", validators = { Validator.NOT_BLANK })String ids,
			@ValidateParam(name = "是否启用 ", validators = { Validator.NOT_BLANK }) Boolean isEnable) {
		managerService.enableManager(isEnable, getAjaxIntegerIds(ids));
		return Result.createSuccessResult();
	}
	
	/**
	 * 
	 * @Description: TODO
	 * @param ids
	 * @return   
	 * Result  
	 * @throws
	 * @author hdt
	 * @date 下午2:45:50
	 */
	@RequestMapping(value = "manager/delete", method = RequestMethod.POST)
	public @ResponseBody Result delete(@ValidateParam(name = "ids", validators = { Validator.NOT_BLANK }) String ids) {
		return Result.createSuccessResult().setData(managerService.deleteManagerById(getAjaxIntegerIds(ids)));
	}
	
	/**
	 * 重置密码
	 * @Description: TODO
	 * @param ids
	 * @return   
	 * Result  
	 * @throws
	 * @author hdt
	 * @date 下午2:48:22
	 */
	@RequestMapping(value = "manager/resetPassword", method = RequestMethod.POST)
	public @ResponseBody Result resetPassword(
			@ValidateParam(name = "ids", validators = { Validator.NOT_BLANK }) String ids) {
		managerService.resetManagerPassword(PasswordProvider.encrypt("123456"), getAjaxIntegerIds(ids));
		return Result.createSuccessResult();
	}
	
	/**
	 * 分配角色
	 * @Description: TODO
	 * @param appId
	 * @param userId
	 * @param roleIds
	 * @return   
	 * Result  
	 * @throws
	 * @author hdt
	 * @date 下午2:53:50
	 */
	@RequestMapping(value = "manager/allocateSave", method = RequestMethod.POST)
	public @ResponseBody Result allocateSave(
			@ValidateParam(name = "管理员ID", validators = { Validator.NOT_BLANK }) Integer userId,
			@ValidateParam(name = "角色IDS ") String roleIds) {
		List<Integer> idList = getAjaxIntegerIds(roleIds);
		List<UserRole> list = new ArrayList<UserRole>();
		UserRole bean = null;
		for (Integer roleId : idList) {
			bean = new UserRole();
			bean.setUserId(userId);
			bean.setRoleId(roleId);
			list.add(bean);
		}
		return Result.createSuccessResult(managerService.allocateUserRole(userId, list), "授权成功");
	}

	@RequestMapping(value = "manager/allocate", method = RequestMethod.GET)
	public String editManagerRole(@ValidateParam(name = "管理员Id", validators = { Validator.NOT_BLANK }) Integer userId, 
			Model model,HttpSession httpSession) {
		model.addAttribute("userId", userId);
		
		List<Role> roleList = managerService.getRoleList(userId);
		
		model.addAttribute("roleList", roleList);
		return "/admin/admin/userRole";
	}
	
	
}